// 获取应用实例
const app = getApp()
Page({
  data: {
    show: 0,
    tel:'',
    userInfo: {},
    list: [],
    listdata: {},
    id: "",
    ids: "", //上个页面的数据
    hasUserInfo: false,
    sumPrice: 0, //总价
    discountPrice: 0, //优惠总价
    discount: 0, //优惠多少钱
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.showModal({
      title: '系统提示',
      content: '更改头像信息？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  aa(e) {
    console.log(e.currentTarget.dataset.key)
    this.setData({
      show: e.currentTarget.dataset.key
    })
  },
  onLoad(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    this.setData({
      ids: options.ids.split(","),
      id: options.id,
      sumPrice: wx.getStorageSync("sumPrice"),
      discountPrice: wx.getStorageSync("discountPrice"),
      ids: options.ids ? options.ids.split(",") : [],
      discount: wx.getStorageSync("discount")
    })
    this.getList();
  },
  // 获取列表
  getList() {
  //  let token = JSON.parse(wx.getStorageSync("token"))
    let token = wx.getStorageSync("token")?JSON.parse(wx.getStorageSync("token")):''
    let that = this;
    wx.request({
      url: 'https://api.jiudaifu.com/v2/acupoint/subject/activitylist',
      data: {
        planteform: 'android',
        username:token.uid
        // username: '20140010',
      },
      method: 'GET',
      header: {
        'content-type': 'application/json', // 默认值
      },
      success: function (res) {
        let list = res.data.data.list;
        var list1 = []
        list.forEach(item => {
          that.data.ids.forEach(v => {
            if (item.id == v) {
              list1.push(item)
            }
          })
        })

        // 获取详情
        wx.request({
          url: 'https://api.jiudaifu.com/v2/acupoint/subject/info2',
          data: {
            id: that.data.id,

            planteform: 'android',
            // username: '20140010',
            username:token.uid
          },
          header: {
            'content-type': 'application/json', // 默认值
          },
          success: function (res) {
            console.log("详情返回数据", res.data.data);
            let restr = res.data.data.subject;
            list1.unshift(restr);
            that.setData({
              list: list1
            })
          },
        })
      },
      fail: function (res) {
        console.log(res)
      }
    });
  },

  // 去支付
  goPay() {
    let that = this;
    let token = wx.getStorageSync("token")?JSON.parse(wx.getStorageSync("token")):''
    let openid = wx.getStorageSync('openid')? wx.getStorageSync('openid'):''
    //  console.log(openid)
    //  console.log(token.uid,openid,this.data.id,this.data.ids)
    //  console.log(this.data.list[0].title,this.data.discountPrice)
    
    if (this.data.ids.length == 0) {
      console.log(11111111111)
      wx.request({
        url: 'https://api.jiudaifu.com/v2/payment/getXiaochengXuOrder', //仅为示例，并非真实的接口地址
        data: {
          username: token.uid,
          subjectId: that.data.id,
          real_price: that.data.discountPrice,
           good_name: that.data.list[0].title,
          openid: openid
        },
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': 'Bearer ' + token.token
        },
        success: function(res) {
          console.log("checkActivationStatus   data = ",res.data);
          if(res.data.error == 0){
            var orderInfo = res.data.data;
            wx.requestPayment({
              nonceStr: orderInfo.nonceStr,
              package: orderInfo.package,
              paySign: orderInfo.sign,
              timeStamp: String(orderInfo.timeStamp),
              signType:orderInfo.signType,
              success:function(e){
                console.log('支付成功');
                wx.navigateTo({
                  url: '/pages/pay/pay',
                })
              },
              fail:function(e){
                console.log("支付失败 =",e);
              }
            })
          }
        },
        fail:function(res){
       
        }
      });
    } else {
  //    console.log(22222222,that.data.ids)
      that.data.ids.unshift(that.data.id)
      let arr = that.data.ids.join(",");
      console.log(arr)
      wx.request({
        url: 'https://api.jiudaifu.com/v2/payment/getActivityOrder', //测试接口
        data: {
          username: token.uid,
         // subjectIds: that.data.ids,
           subjectIds: arr,
          real_price: that.data.discountPrice,
          good_name: '组合套餐',
          openid: openid
        },
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': 'Bearer ' + token
        },
        success: function (res) {
          console.log("checkActivationStatus   data = ", res.data);
          if (res.data.error == 0) {
            var orderInfo = res.data.data;
            wx.requestPayment({
              nonceStr: orderInfo.nonceStr,
              package: orderInfo.package,
              paySign: orderInfo.sign,
              timeStamp: String(orderInfo.timeStamp),
              signType: orderInfo.signType,
              success: function (e) {
                console.log('支付成功');
                wx.navigateTo({
                  url: '/pages/pay/pay',
                })
              },
              fail: function (e) { 
                console.log("支付失败 =", e);
              }
            })
          }
        },
        fail: function (res) {}
      });
    }
  },
  goDetail(e){
  let ids = e.target.dataset.key
   console.log(ids)
   wx.navigateTo({
    url: `/pages/listdetail/listdetail?ids=${ids}`
  });
 },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  onShow(){
    let userlist =  wx.getStorageSync("userInfo") ? JSON.parse(wx.getStorageSync("userInfo")) : ''
    this.setData({
      tel:userlist.mobile
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})